
import Taro, { useRouter } from "@tarojs/taro";
import { PageContainer, View } from "@tarojs/components";
import { useCreation, useResetState } from "ahooks";
import pick from "lodash-es/pick";
import dayjs from "dayjs";

import ByTag from "@/components/ui/ByTag";
import ByCell from "@/components/ui/ByCell";
import Card from "@/components/common/Card";
import Page from "@/components/common/Page";
import ByIcon from "@/components/ui/ByIcon";
import ByText from "@/components/ui/ByText";
import Moment from "@/components/app/Moment";
import BySpace from "@/components/ui/BySpace";
import ByButton from "@/components/ui/ByButton";
import Uploader from "@/components/app/Uploader";
import ByStepsItem from "@/components/ui/ByStepsItem";
import FormInput from "@/components/common/FormInput";
import ByCellGroup from "@/components/ui/ByCellGroup";
import PopupMember from "@/components/app/PopupMember";
import ByImageGroup from "@/components/ui/ByImageGroup";
import TagRadioGroup from "@/components/app/TagRadioGroup";
import PopupRepairOrder from "./components/PopupRepairOrder";
import FormInputNumber from "@/components/common/FormInputNumber";

import ApiCrm from "@/api/crm";
import ApiFinance from "@/api/finance";
import useEnum from "@/hooks/useEnum";
import useForm from "@/hooks/useForm";
import useFetch from "@/hooks/useFetch";
import useWorkflowDefinition from "@/hooks/useWorkflowDefinition";

import { IntentCustomerData } from "@/types/customer";


type FormModel = {
  intentCustomerId: number;
  /**
   * 售后工单ID
   */
  afterSaleOrderId: number;
  /**
   * 付款对象类型 0:施工人员,1:供应商，2:工人
   */
  tagetUserType: number;
  tagetUserId: number;
  tagetUserName: string;
  /**
   * 申请金额
   */
  applyAmount: number;
  /**
   * 付款阶段
   */
  paymentStage: string;
  /**
   * 费用类别
   */
  feeCategory: string;
  /**
   * 摘要
   */
  summary: string;
  /**
   * 备注
   */
  remark?: string;
  /**
   * 附件ID
   */
  fileRefererId?: string[];

  repairBillId: number;
  repairContent: string;
  contractAmount: number;
};

const tagProps = {
  variant: "outline",
  size: "small",
} as const;

const rules = {
  tagetUserId: { required: true, message: "请选择维修负责人" },
  applyAmount: { required: true, message: "请填写申请金额" },
  summary: { required: true, message: "请填写保修内容" },
  feeCategory: { required: true, message: "请选择售后类型" },
};

export default () => {
  const { params } = useRouter<{
    intentCustomerId: `${number}`;
  }>();

  const intentCustomerId = +params.intentCustomerId;

  // 客户详情
  const { data } = useFetch<IntentCustomerData>(ApiCrm.customerDetail, {
    defaultParams: [{ intentCustomerId }],
    showLoading: true,
    onAfter: (res: any) => res.intentCustomer,
  });

  const { data: planData } = useFetch<{ realStartDate: string, realEndDate: string }>(ApiCrm.getConstructionPlanDetail, { defaultParams: [{ intentionCustomerId: intentCustomerId }] })

  // 售后审批工作流
  const [workflowDefined, { loading: bindLoading, bind }] = useWorkflowDefinition(
    { typeCode: "AS_WorkerLaborCostApply" },
    {
      onSuccess(res: any, [param]) {
        Taro.showToast({ title: "创建成功！" });
        setTimeout(() => {
          Taro.redirectTo({
            url: `detail?intentCustomerId=${intentCustomerId}&businessId=${param.businessId}&wl_id=${res.workflowInstanceId}`,
          });
        });
      }
    }
  );

  // 创建售后接口
  const { loading, model, setModel, submit } = useForm<FormModel>(
    ApiFinance.afterSaleCreate,
    {
      rules,
      defaultModel: { intentCustomerId, fileRefererId: [] },
      onSuccess(res: {
        /**
         * 单据编号
         */
        billNo: string;
        /**
         * 付款单ID
         */
        paymentBillId: number;
      }) {
        bind({
          intentCustomerId,
          businessId: res.paymentBillId + ""
        });
      },
    }
  );

  const [visible, setVisible, resetVisible] = useResetState<
    "member" | "repair" | undefined
  >(undefined);

  //  0:EPR人员,1:供应商，2:工人
  const handlePickerChange = (e, type) => {
    switch (type) {
      case "supplier":
        setModel({
          tagetUserType: 1,
          tagetUserId: e.supplyId,
          tagetUserName: e.supplyName,
        });
        break;

      case "erp":
        setModel({
          tagetUserType: 0,
          tagetUserId: e.user_id,
          tagetUserName: e.user_name,
        });
        break;

      case "worker":
        setModel({
          tagetUserType: 2,
          tagetUserId: e.workerId,
          tagetUserName: e.workerName,
        });
        break;
    }

    resetVisible();
  };

  // 维修单选择
  const handleRepairChange = (repair) => {
    setModel(pick(repair, ["repairBillId", "repairContent", "contractAmount"]));
    resetVisible();
  };

  // 售后类型Options 选项
  const { options } = useEnum({ className: "公司类型" });


  // 是否在质保期内
  const isValid = useCreation(() => {
    const { planWarrantyDate: date } = data || {}
    if (!date) return false
    return dayjs().isSameOrBefore(date)
  }, [data])

  return (
    <>
      <Page
        footerSticky
        slotFooter={
          <ByButton
            size="large"
            className="w-2/3"
            loading={loading || bindLoading}
            onClick={() => submit()}
          >
            提交
          </ByButton>
        }
      >
        <Card className="m-3">
          <View className="font-bold text-lg">{data?.customerName}</View>
          <View className="mt-2 text-second text-sm">
            {data?.decorationFullAddress}
          </View>
        </Card>

        <Card className="m-3">
          <ByCell label="施工工期：" size="small">
            <Moment value={planData?.realStartDate} />
            ~
            <Moment value={planData?.realEndDate} />
          </ByCell>
          <ByCell label="质保期：" size="small">
            <ByText className="mr-2">{data?.planWarrantyDate} 截至</ByText>
            <ByText type={isValid ? 'primary' : 'error'}>{isValid ? '质保中' : '质保结束'}</ByText>
          </ByCell>
        </Card>

        <ByCellGroup className="m-3">
          <ByCell label="售后维修单" vertical requierd>
            <FormInput
              disabled
              placeholder="选择售后维修单"
              value={
                model.repairBillId
                  ? `${model.repairContent}(¥${model.contractAmount})`
                  : ""
              }
              suffix={<ByIcon name="ArrowBottom" />}
              onClick={() => setVisible("repair")}
            />
          </ByCell>

          <ByCell label="维修负责人" vertical requierd>
            <FormInput
              disabled
              placeholder="选择维修负责人"
              value={model.tagetUserName}
              suffix={<ByIcon name="ArrowBottom" />}
              onClick={() => setVisible("member")}
            />
          </ByCell>

          <ByCell label="申请金额" vertical requierd>
            <FormInputNumber
              prefix={<ByText type="third">¥</ByText>}
              precision={2}
              placeholder="输入金额"
              defaultValue={0}
              onChange={(e) => setModel({ applyAmount: e })}
            />
          </ByCell>

          <ByCell label="保修内容" vertical requierd>
            <FormInput
              type="textarea"
              value={model.summary}
              placeholder="输入保修内容"
              rows={6}
              onChange={(e) => setModel({ summary: e })}
            />
          </ByCell>

          <ByCell label="备注" vertical>
            <FormInput
              type="textarea"
              value={model.remark}
              placeholder="备注"
              rows={6}
              onChange={(e) => setModel({ remark: e })}
            />
          </ByCell>
        </ByCellGroup>

        <ByCellGroup className="m-3">
          <ByCell label="售后类型" vertical requierd>
            <TagRadioGroup
              value={[model.feeCategory]}
              options={options}
              labelKey="label"
              valueKey="label"
              onChange={([e]) => setModel({ feeCategory: e })}
            />
          </ByCell>
          <ByCell label="附件" vertical>
            <ByImageGroup
              showDelete
              urls={model.fileRefererId}
              onChange={(res) => setModel({ fileRefererId: res })}
              slotFooter={
                <Uploader
                  onSuccess={(res) =>
                    setModel({
                      fileRefererId: model.fileRefererId?.concat(res),
                    })
                  }
                />
              }
            />
          </ByCell>
        </ByCellGroup>

        <ByCellGroup className="m-3" title="审批流程">
          <View className="py-3">
            {workflowDefined[0]?.steps.map((item) => (
              <ByStepsItem
                key={item.nodeId}
                title={item.nodeName}
                date={item.approvers.length > 0 ? "1人通过即可" : ""}
              >
                <BySpace gap={8}>
                  {item.approvers.map((approver) => (
                    <ByTag key={approver.actorId} {...tagProps}>
                      {approver.actorName}
                    </ByTag>
                  ))}
                </BySpace>
              </ByStepsItem>
            ))}
          </View>
        </ByCellGroup>
      </Page>

      <PageContainer
        round
        show={!!visible}
        close-on-slide-down
        onAfterLeave={resetVisible}
      >
        {visible === "repair" ? (
          <PopupRepairOrder
            intentCustomerId={intentCustomerId}
            repairBillId={model.repairBillId}
            onCancel={resetVisible}
            onConfirm={handleRepairChange}
          />
        ) : visible === "member" ? (
          <PopupMember
            title="维修负责人"
            type={["erp", "supplier"]}
            onCancel={resetVisible}
            onConfirm={handlePickerChange}
          />
        ) : null}
      </PageContainer>
    </>
  );
};
